package com.rent.auth.service.impl;

import com.rent.auth.service.IMyBaseService;
import com.rent.common.utils.StringUtils;
import com.database.service.impl.SuperServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.io.Serializable;

/**
 * @Author zhang
 * @create 2023/7/29 15:34
 */
@Service
public abstract class MyBaseService<M extends com.database.mapper.BaseMapper<T, PK>, T, PK extends Serializable> extends SuperServiceImpl<M, T, PK> implements IMyBaseService<T, PK> {

    public static final String NET_PROTOCOL = "http://";

    public static final String AUTHORIZE_TOKEN = "Authorization";

    public static final String TOKEN_HEADER = "Bearer ";

    public static final String GRAND_TYPE_REFRESH = "refresh_token";

    /***
     * base64编码
     */
    public String httpBasic(String clientId, String clientSecret) {
        //将客户端id和客户端密码拼接，按“客户端id:客户端密码”
        String string = clientId + ":" + clientSecret;
        //进行base64编码
        byte[] encode = Base64Utils.encode(string.getBytes());
        return "Basic " + new String(encode);
    }

    public String getAuthorizeToken() {
        HttpServletRequest request = ((ServletRequestAttributes) (RequestContextHolder.currentRequestAttributes())).getRequest();
        // 头文件中获取token
        String token = request.getHeader(AUTHORIZE_TOKEN);
        // cookie中获取token
        if (StringUtils.isEmpty(token)) {
            //4.2 从cookie中中获取令牌数据
            Cookie[] cookies = request.getCookies();
            if (cookies != null) {
                for (Cookie cookie : cookies) {
                    if (cookie.getName().equalsIgnoreCase(AUTHORIZE_TOKEN)) {
                        token = cookie.getValue();
                        break;
                    }
                }
            }
        }
        // 获取参数中的token
        if (StringUtils.isEmpty(token)) {
            //4.3 从请求参数中获取令牌数据
            token = request.getParameter(AUTHORIZE_TOKEN);
        }
        //添加头信息 Bearer
        if (!StringUtils.isEmpty(token)) {
            //4.4. 如果没有数据    没有登录,要重定向到登录到页面
            if (token.startsWith("bearer ") || token.startsWith("Bearer ")) {
                token = token.substring(7);
            }
        } else {
            token = null;
        }
        return token;
    }

}
